package com.mingtu.guards.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.basic.PictureMediaScannerConnection;
import com.luck.picture.lib.basic.PictureSelectionPreviewModel;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnCallbackListener;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DownloadFileUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.InfraredRecordPicDetailsActivity;
import com.mingtu.guards.bean.InfraredRecordImgBean;
import com.mingtu.guards.share.BottomPopupShare2;
import com.mob.MobSDK;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static com.mingtu.guards.base.Application.hideMyDownLoadDialog;
import static com.mingtu.guards.base.Application.showMyDownLoadDialog;
import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class InfrareGroupPictureAdapter extends RecyclerView.Adapter<InfrareGroupPictureAdapter.ActivityHolder> implements View.OnClickListener {
    private Context context;
    private Map<String, List<InfraredRecordImgBean.DataBean.ListBean>> mData;
    private OnItemClickListener mOnItemClickListener = null;
    private List<String> timeData = new ArrayList<>(); //存放键-  时间
    private List<List<InfraredRecordImgBean.DataBean.ListBean>> pictureData = new ArrayList<>(); //存放值 -图片
    private Activity activity;

    public InfrareGroupPictureAdapter(Activity activity, Context context) {
        this.activity = activity;
        this.context = context;
    }

    @Override
    public ActivityHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 实例化展示的view
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_picture_group, parent, false);
        // 实例化viewholder
        ActivityHolder viewHolder = new ActivityHolder(view);
        viewHolder.itemView.setOnClickListener(this);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ActivityHolder holder, int position) {
        if (mData != null) {
            if (mData.size() > 0) {
                String time = timeData.get(position);
                List<InfraredRecordImgBean.DataBean.ListBean> listBeans = pictureData.get(position);
                holder.tvTime.setText(time);

                ArrayList<LocalMedia> localMediaList = new ArrayList<>();
                if (listBeans != null && listBeans.size() > 0) {
                    for (InfraredRecordImgBean.DataBean.ListBean listBean : listBeans) {
                        String url = listBean.getUrl();
                        String cameraName = listBean.getCameraName();
                        String createTime = listBean.getCreateTime();
                        LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
                        localMedia.setRealPath(url);
                        localMedia.setFileName(cameraName + "号红外相机" + createTime + "拍摄");
                        localMediaList.add(localMedia);
                    }

                }
                InfraredPictureAdapter infraredPictureAdapter = null;
                if (infraredPictureAdapter == null) {
                    infraredPictureAdapter = new InfraredPictureAdapter(context, listBeans);
                    GridLayoutManager layoutManager = new GridLayoutManager(context, 2);//第二个参数为网格的列数
                    holder.recycler.setLayoutManager(layoutManager);

                    if (holder.recycler.getItemDecorationCount() > 0) { //解决RecycleView嵌套后重复调用addItemDecoration方法使间隔增大
                        RecyclerView.ItemDecoration itemDecorationAt = holder.recycler.getItemDecorationAt(0);
                        if (itemDecorationAt == null) {
                            holder.recycler.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(ItemDecorationSpaces), true));
                        }
                    } else {
                        //需要在setLayoutManager()之后调用addItemDecoration()
                        holder.recycler.addItemDecoration(new GridSpacingItemDecoration(2, SizeUtils.dp2px(ItemDecorationSpaces), true));
                    }

                    holder.recycler.setHasFixedSize(true); //当知道Adapter内Item的改变不会影响RecyclerView宽高的时候，可以设置为true让RecyclerView避免重新计算大小
                    holder.recycler.setAdapter(infraredPictureAdapter);

                } else {
                    infraredPictureAdapter.upData(listBeans);
                }
                infraredPictureAdapter.setOnItemClickListener(new InfraredPictureAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int p) {

                        if (listBeans != null) {
                            if (listBeans.size() > 0) {
                                boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
                                if (!isLeader) {
                                    if (localMediaList.size() > 0) {

                                        PictureSelectorStyle selectorStyle = BaseApplication.getSelectorStyle();
                                        TitleBarStyle titleBarStyle = selectorStyle.getTitleBarStyle();
                                        titleBarStyle.setPreviewDeleteBackgroundResource(R.mipmap.icon_three_circle);
                                        selectorStyle.setTitleBarStyle(titleBarStyle);

                                        PictureSelectionPreviewModel previewModel = BaseApplication.initPreviewModel();
                                        previewModel.setSelectorUIStyle(selectorStyle);
                                        previewModel.startActivityPreview(p, true, localMediaList);
                                        previewModel.setExternalPreviewEventListener(new MyOnExternalPreviewEventListener(localMediaList));


                                    }
                                } else {

                                    //识别结果
                                    ArrayList<Object> list = new ArrayList<Object>();
                                    list.add(listBeans.get(p));

                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable("object", list);
                                    IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), InfraredRecordPicDetailsActivity.class, bundle);
                                }

                            } else {
                                ToastUtils.showLong(context.getString(R.string.data_error));
                            }
                        } else {
                            ToastUtils.showLong(context.getString(R.string.data_error));
                        }
                    }
                });
            }
        }
        //将position保存在itemView的Tag中，以便点击时进行获取
        holder.itemView.setTag(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public void onClick(View v) {
        if (mOnItemClickListener != null) {
            //注意这里使用tag方法获取position
            mOnItemClickListener.onItemClick(v, (int) v.getTag());
        }
    }

    private class MyOnExternalPreviewEventListener implements OnExternalPreviewEventListener {
        private ArrayList<LocalMedia> localMedia;
        private BasePopupView popupView;

        public MyOnExternalPreviewEventListener(ArrayList<LocalMedia> pictureMediaList) {
            this.localMedia = pictureMediaList;
        }

        @Override
        public void onPreviewDelete(int position) {
            LocalMedia media = localMedia.get(position);
            String imgUrl = media.getRealPath();
            String fileName = media.getFileName();
            String content = "绿水青山就是金山银山";
            Bitmap imageData = MyUtills.drawable2Bitmap(context.getResources().getDrawable(R.drawable.bg_shared_img));
            final OnekeyShare oks = new OnekeyShare();
            oks.setText(fileName);
            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
            oks.setTitle(content);
            oks.setTitleUrl("https://www.mingtukeji.com");
            // text是分享文本，所有平台都需要这个字段
            //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//                        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setImageData(imageData);
            oks.setImageUrl(imgUrl);
            oks.setUrl(imgUrl);

            BottomPopupShare2 bottomPopup = new BottomPopupShare2(ActivityUtils.getTopActivity());
            bottomPopup.setOnItemClickListener(new BottomPopupShare2.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    popupView.dismiss();
                    switch (position) {
                        case 0:
                            oks.setPlatform(Wechat.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 1:
                            oks.setPlatform(WechatMoments.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 2:
                            oks.setPlatform(WechatFavorite.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 3:
                            String path = media.getAvailablePath();
                            if (PictureMimeType.isHasHttp(path)) {
                                showMyDownLoadDialog();
                            }
                            DownloadFileUtils.saveLocalFile(context, path, media.getMimeType(), new OnCallbackListener<String>() {
                                @Override
                                public void onCall(String realPath) {
                                    hideMyDownLoadDialog();
                                    if (TextUtils.isEmpty(realPath)) {
                                        String errorMsg;
                                        if (PictureMimeType.isHasAudio(media.getMimeType())) {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_audio_error);
                                        } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_video_error);
                                        } else {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_image_error);
                                        }
                                        com.luck.picture.lib.utils.ToastUtils.showToast(context, errorMsg);
                                    } else {
                                        new PictureMediaScannerConnection(ActivityUtils.getTopActivity(), realPath);
                                        com.luck.picture.lib.utils.ToastUtils.showToast(context, context.getString(com.luck.picture.lib.R.string.ps_save_success) + "\n" + realPath);
                                    }
                                }
                            });
                            break;
                    }
                }
            });
            popupView = new XPopup.Builder(ActivityUtils.getTopActivity())
                    .navigationBarColor(context.getResources().getColor(R.color.white))
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCustom(bottomPopup)
                    .show();
        }

        @Override
        public boolean onLongPressDownload(Context context, LocalMedia media) {

            return false;
        }
    }

    public void upData(Map<String, List<InfraredRecordImgBean.DataBean.ListBean>> data) {
        mData = data;
        timeData = new ArrayList<>();
        pictureData = new ArrayList<>();

        for (Map.Entry<String, List<InfraredRecordImgBean.DataBean.ListBean>> itemMap : mData.entrySet()) {
            String time = itemMap.getKey();
            List<InfraredRecordImgBean.DataBean.ListBean> listBeans = itemMap.getValue();
            timeData.add(time);
            pictureData.add(listBeans);
        }

        notifyDataSetChanged();
    }

    public void clearData() {
        if (mData != null) {
            mData.clear();
        }
    }


    /**
     * 获取时间数据
     *
     * @return
     */
    public List<String> getTimeData() {
        return timeData;
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }


    public static interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

    public static class ActivityHolder extends RecyclerView.ViewHolder {
        private final View convertView;
        private TextView tvTime;
        private RecyclerView recycler;

        public ActivityHolder(View itemView) {
            super(itemView);
            convertView = itemView;
            tvTime = (TextView) convertView.findViewById(R.id.tv_time);
            recycler = (RecyclerView) convertView.findViewById(R.id.recycler);
        }
    }


}
